#!/usr/bin/env bash
# Main script deploy work on server


# Get setting info
#source "$(pwd)/syn-setting"
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
source "$DIR/syn-setting"

while getopts :n:d:h opt
do case "$opt" in
	n) local="" ;;
	d) dest="" ;;
	h)  echo
		echo "Usage: sync-deploy -n local_files -d 'destdir'"
		echo ">>> local_files: files you wanna upload, can be directories or filenames"
		echo ">>> destdir: The only one directory you wanna transfer to."
		echo ">>>          Do not set more than one destdir, error will occur."
		echo ">>>  	Please do note the 'destdir' must be quoted otherwise you use absolute file path!!!"
		echo ">>>"
		echo ">>> examples:"
		echo "              sync-deploy -n work.sh -d /public/home/liuxs/test"
		echo "         or"
		echo "              sync-deploy -n work.sh -d '~/test'"
        echo
        exit ;;
	*) echo "Unknown option: $opt"
		echo
		sync-deploy -h
        exit ;;
	esac
done

#echo all variables  $*

local=$(echo "$*" | sed -E 's/-n (.*) -d (.*)$/\1/')
dest=$(echo "$*" | sed -E 's/-n (.*) -d (.*)$/\2/')

# if variable name is not set, show help info
if [ ! -n "$local" ]; then
	sync-deploy -h
	exit
fi

# if variable dir is not set, show help info
if [ ! -n "$dest" ]; then
	sync-deploy -h
	exit
fi

# if variable port is not set, set 22 as default
if [ ! -n "$port" ]; then
	port=22
fi

#  generate work script
# $DIR/generate_work_sh.sh

# 1. upload files to server
sync-upload -n $local -d $dest

# 2. run task one by one on remote server
for tk in $local
do
	sync-run -f $dest/$tk -t # -f Following file path on remote server
	if [ $? -ne 0 ]; then
		echo "Error! There is something wrong in this deploy, please check it."
		exit
	fi
done

#ssh -p $port $remote_user@$remote_ip "qstat $job_id" | awk  '$1 ~/'$job_id'/ {print $5}'

sleep 0.3
echo ">>>"
echo ">>> The work deploy successfully."
echo
# done
